package global

import (
	"context"
	_const "github.com/flipped-aurora/gin-vue-admin/server/global/const"
	request_model "github.com/flipped-aurora/gin-vue-admin/server/model/im/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/im/response"
	"github.com/flipped-aurora/gin-vue-admin/server/utils/cache"
	"github.com/flipped-aurora/gin-vue-admin/server/utils/request"
	"github.com/mitchellh/mapstructure"
	"github.com/pkg/errors"
	"strconv"
	"time"
)

// IMAdminTokenCache im系统管理员token的缓存
var IMAdminTokenCache = cache.New(IMAdminTokenLoader)

var IMAdminTokenLoader = func(_ctx context.Context) (interface{}, int64, error) {
	var imAdminTokenUrl = _const.OpenImServerAddress + "/auth/get_admin_token"
	var reqData = request_model.IMAdminTokenRequest{
		UserID: "imAdmin",
		Secret: "openIM123",
	}
	var headers = make(map[string]string, 1)
	headers[request_model.OpenIMOperationIDHeader] = strconv.Itoa(time.Now().Second())
	var openImResp = response.OpenImResponse{}
	var _, errReq = request.HttpRequest(imAdminTokenUrl, request.POST, headers, request.EmptyParams, reqData, &openImResp)
	if errReq != nil {
		return nil, 0, errReq
	}

	if openImResp.ErrCode != 0 {
		return nil, 0, errors.Errorf("unexpected openim code %s, err_dlt: %s",
			openImResp.ErrCode, openImResp.ErrDlt)
	}

	var tokenData = response.TokenResponseData{}

	if err := mapstructure.Decode(openImResp.Data, &tokenData); err != nil {
		return nil, 0, errors.Errorf("admin_token_data mapstruct failed! %w, raw_data=%v",
			err, openImResp.Data)
	}

	return tokenData.Token, tokenData.ExpireTimeSeconds, nil
}
